import { Button, Card, Modal, Space, Table } from "antd";
import { ColumnsType } from "antd/lib/table";
import React, { useCallback, useEffect, useState } from "react";
import { deleteGroup, getGroup, getTaskList, useTaskRoot, uploadGroup, updateGroup } from "../../api";
import AddTaskModal from "../AddTaskModal";

interface ListProps { }

const List: React.FC<ListProps> = () => {
  const taskRoot = useTaskRoot();
  const [taskList, setTaskList] = useState<any[]>([]);
  const [currentTask, setCurrentItem] = useState<any>();

  // 获取任务根目录，更新任务列表
  useEffect(() => {
    (async () => setTaskList(await getTaskList(taskRoot)))()
  }, [taskRoot]);

  const [isAddModalOpen, setIsAddModalOpen] = useState<boolean>(false);

  // 打开新建任务对话框
  const showAddModal = useCallback((item: any) => setIsAddModalOpen(true), []);

  const handleAddModalOk = useCallback(async (data: any[]) => {
    console.log("data", data);

    // 构建任务描述
    const task = JSON.parse(data[0]);
    const { flowContents: { controllerServices, processors } } = task;
    [...controllerServices, ...processors].forEach((item, index) => {
      item.properties = data[1][index];
    });

    const parentGroup = await getGroup(data[3].parentGroupId);

    // 更新任务列表
    let newTask = await uploadGroup(parentGroup, data[3].name, JSON.stringify(task));
    if (data[3].comments) {
      newTask = await updateGroup(newTask, { name: data[3].name, comments: data[3].comments });
    }
    newTask.parentGroup = parentGroup;
    setTaskList([newTask, ...taskList]);

    // 关闭新建任务对话框
    setIsAddModalOpen(false);
  }, [taskList]);

  const handleAddModalCancel = useCallback(() => setIsAddModalOpen(false), []);

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);

  const showDeleteModal = useCallback((item: any) => {
    // 设置当前任务
    setCurrentItem(item);
    // 打开删除确认对话框
    setIsDeleteModalOpen(true);
  }, []);

  const handleDeleteOk = useCallback(async () => {
    // 删除当前任务
    await deleteGroup(currentTask);
    // 更新任务列表
    setTaskList(taskList?.filter(item => item.id !== currentTask.id));
    // 关闭删除确认对话框
    setIsDeleteModalOpen(false);
  }, [currentTask, taskList]);

  // 关闭删除确认对话框
  const handleDeleteCancel = useCallback(() => setIsDeleteModalOpen(false), []);

  const [tableColumns,] = useState<ColumnsType<any>>([
    {
      title: "任务类别",
      key: "category",
      dataIndex: ["parentGroup", "component", "name"],
      onHeaderCell: () => { return { style: { "fontWeight": "bold", "whiteSpace": "nowrap" } } },
      onCell: () => { return { style: { "minWidth": "12em", "fontSize": "small" } } },
    },
    {
      title: "任务名称",
      key: "name",
      //dataIndex: ["component", "name"],
      onHeaderCell: () => { return { style: { "fontWeight": "bold", "whiteSpace": "nowrap" } } },
      onCell: () => { return { style: { "minWidth": "12em", "fontSize": "small" } } },
      render: (value, record, index) => (
        <a href={`#/task/${value.id}`}>{value.component.name}</a>
      ),
    },
    {
      title: "任务说明",
      key: "comments",
      dataIndex: ["component", "comments"],
      width: "100%",
      onHeaderCell: () => { return { style: { "fontWeight": "bold", "whiteSpace": "nowrap" } } },
      onCell: () => { return { style: { "minWidth": "12em", "fontSize": "small" } } },
    },
    {
      title: "操作",
      render: (item) => <Space size="small">
        <Button type="link" target="_blank" href={`/nifi/#/process-groups/${item.id}`}>工作流</Button>
        <Button type="primary" size="small" onClick={() => showAddModal(item)}>启动</Button>
        <Button type="default" size="small" onClick={() => showAddModal(item)}>停止</Button>
        <Button type="default" size="small" onClick={() => showDeleteModal(item)} danger={true}>删除</Button>
      </Space>,
      onHeaderCell: () => { return { style: { "fontWeight": "bold", "whiteSpace": "nowrap", "textAlign": "center" } } },
      onCell: () => { return { style: { "whiteSpace": "nowrap", "fontSize": "small" } } },
    },
  ]);

  return (
    <>
      <Card className="mb-16">
        <h1>任务列表</h1>
      </Card>
      <Card>
        <Space direction="vertical" style={{ 'display': 'flex' }}>
          <Button type="primary" onClick={() => showAddModal(null)}>新建</Button>
          <Table
            size="small"
            columns={tableColumns}
            rowKey="id"
            dataSource={taskList}
            loading={!taskList}
          />
        </Space>
        {isAddModalOpen && <AddTaskModal onAddModalOk={handleAddModalOk} onAddModalCancel={handleAddModalCancel} />}
        <Modal title="删除任务" visible={isDeleteModalOpen} onOk={handleDeleteOk} onCancel={handleDeleteCancel}>
          <p>您正在删除：</p>
          <p>任务名称：{currentTask?.component.name}</p>
          <p>任务说明：{currentTask?.component.comments}</p>
        </Modal>
      </Card>
    </>
  );
};

export default List;
